<!--登录页面-->
<template>
  <div class="login">
    <el-form class="form" :model="model" :rules="rules" ref="loginForm">
      <div class="form-header">
        <h1 class="title">OwO后台管理系统</h1>
        <div class="header-actions">
          <el-button type="text" class="register-btn" @click="showRegister">
            注册账号
          </el-button>
          <change-lang class="lang-switch" />
        </div>
      </div>
      <el-form-item prop="userName">
        <el-input
          class="text"
          v-model="model.userName"
          prefix-icon="User"
          clearable
          :placeholder="$t('login.username')"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="model.password"
          prefix-icon="Lock"
          show-password
          clearable
          :placeholder="$t('login.password')"
        />
      </el-form-item>

      <el-form-item prop="captcha">
        <div class="captcha">
          <el-input
            class="text"
            v-model="model.captcha"
            prefix-icon="Picture"
            placeholder="请输入验证码"
          ></el-input>
          <img :src="captchaSrc" @click="refreshCaptcha" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="submit"
        >
          {{ btnText }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 注册对话框 -->
  <el-dialog v-model="registerVisible" title="注册账号" width="500px">
    <el-form
      :model="registerModel"
      :rules="registerRules"
      ref="registerForm"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="registerModel.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="registerModel.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerModel.confirmPassword"
          type="password"
          placeholder="请确认密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="''"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :http-request="handleFileUpload"
        >
          <img
            v-if="registerModel.avatar"
            :src="registerModel.avatar"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="registerVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="registerLoading"
          @click="submitRegister"
        >
          注册
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
  ref,
  computed,
  onMounted,
  watch,
} from 'vue'
import { Login, GetValidateCode, Register, fileUpload } from '@/api/login'
import { useRouter, useRoute } from 'vue-router'
import ChangeLang from '@/layout/components/Topbar/ChangeLang.vue'
import useLang from '@/i18n/useLang'
import { useApp } from '@/pinia/modules/app'

export default defineComponent({
  components: { ChangeLang },
  name: 'login',
  setup() {
    const { proxy: ctx } = getCurrentInstance() // 可以把ctx当成vue2中的this
    const router = useRouter()
    const route = useRoute()
    const { lang } = useLang()
    watch(lang, () => {
      state.rules = getRules()
      state.registerRules = getRegisterRules()
    })
    const getRules = () => ({
      userName: [
        {
          required: true,
          message: ctx.$t('login.rules-username'),
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: ctx.$t('login.rules-password'),
          trigger: 'blur',
        },
        {
          min: 6,
          max: 12,
          message: ctx.$t('login.rules-regpassword'),
          trigger: 'blur',
        },
      ],
      captcha: [
        {
          required: true,
          message: ctx.$t('login.rules-validate-code'),
          trigger: 'blur',
        },
      ],
    })

    const getRegisterRules = () => ({
      userName: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
        {
          min: 6,
          max: 12,
          message: '密码长度在6到12个字符',
          trigger: 'blur',
        },
      ],
      confirmPassword: [
        {
          required: true,
          message: '请确认密码',
          trigger: 'blur',
        },
        {
          validator: (rule, value, callback) => {
            if (value !== state.registerModel.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur',
        },
      ],
    })

    // onMounted钩子函数
    onMounted(() => {
      state.refreshCaptcha()
    })

    const state = reactive({
      model: {
        userName: 'admin',
        password: '111111',
        captcha: '', // 用户输入的验证码
        codeKey: '', // 后端返回的验证码key
      },
      rules: getRules(),
      loading: false,
      captchaSrc: '',
      registerVisible: false,
      registerModel: {
        userName: '',
        password: '',
        confirmPassword: '',
        name: '',
        phone: '',
        avatar: '',
        description: '',
      },
      registerRules: getRegisterRules(),
      registerLoading: false,
      refreshCaptcha: async () => {
        const { data } = await GetValidateCode()
        state.model.codeKey = data.codeKey
        state.captchaSrc = data.codeValue
      },
      btnText: computed(() =>
        state.loading ? ctx.$t('login.logining') : ctx.$t('login.login')
      ),
      loginForm: ref(null),
      registerForm: ref(null),
      submit: () => {
        if (state.loading) {
          return
        }
        state.loginForm.validate(async valid => {
          if (valid) {
            state.loading = true
            const { code, data, message } = await Login(state.model)
            if (code === 200) {
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/') // 请求成功以后，进入到首页
              }
              useApp().initToken(data)
            } else {
              ctx.$message.error(message)
            }
            state.loading = false
          }
        })
      },
      submitRegister: () => {
        if (state.registerLoading) return

        state.registerForm.validate(async valid => {
          if (valid) {
            state.registerLoading = true
            try {
              const { code, message } = await Register(state.registerModel)
              if (code === 200) {
                ctx.$message.success('注册成功')
                state.registerVisible = false
                // 清空表单
                state.registerModel = {
                  userName: '',
                  password: '',
                  confirmPassword: '',
                  name: '',
                  phone: '',
                  avatar: '',
                  description: '',
                }
              } else {
                ctx.$message.error(message || '注册失败')
              }
            } catch (error) {
              ctx.$message.error('注册失败')
            } finally {
              state.registerLoading = false
            }
          }
        })
      },
      handleAvatarSuccess: res => {
        if (res.code === 200) {
          state.registerModel.avatar = res.data
        } else {
          ctx.$message.error('上传失败')
        }
      },
      beforeAvatarUpload: file => {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          ctx.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        }
        if (!isLt2M) {
          ctx.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
    })

    const handleFileUpload = options => {
      const file = options.file
      fileUpload(file)
        .then(res => {
          if (res.code === 200) {
            console.log('res', res)
            state.registerModel.avatar = res.data
            options.onSuccess(res)
          } else {
            options.onError(new Error('上传失败'))
          }
        })
        .catch(err => {
          options.onError(err)
        })
    }

    const showRegister = () => {
      state.registerVisible = true
    }

    return {
      ...toRefs(state),
      showRegister,
      handleFileUpload,
    }
  },
})
</script>

<style lang="scss" scoped>
.login {
  transition: transform 1s;
  transform: scale(1);
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #2d3a4b;
  .form {
    width: 520px;
    max-width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 160px auto 0;
    :deep {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
        background: rgba(0, 0, 0, 0.1);
      }
      .el-input-group--append > .el-input__wrapper {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .el-input-group--prepend > .el-input__wrapper {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      .title {
        color: #fff;
        font-size: 24px;
        margin: 0;
      }
      .header-actions {
        display: flex;
        align-items: center;
        gap: 16px;
        .register-btn {
          color: #fff;
          &:hover {
            color: #409eff;
          }
        }
        .lang-switch {
          :deep(.change-lang) {
            height: 24px;
            &:hover {
              background: none;
            }
            .icon {
              color: #fff;
            }
          }
        }
      }
    }
    .title {
      color: #fff;
      text-align: center;
      font-size: 24px;
      margin: 0 0 24px;
    }
    .text {
      font-size: 16px;
      :deep(.el-input__inner) {
        color: #fff;
        height: 48px;
        line-height: 48px;
        &::placeholder {
          color: rgba(255, 255, 255, 0.2);
        }
      }
    }
    .btn {
      width: 100%;
    }
  }
}

.captcha {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.captcha img {
  cursor: pointer;
  margin-left: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
}

// 移除原有的change-lang样式
.change-lang {
  display: none;
}
</style>
